package com.v1.video;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.SurfaceHolder;

import com.common.core.CommonCoreApplication;
import com.common.core.CoreConfiguration;
import com.common.core.utils.AppUtils;
import com.common.filedownloader.FileDownloader;
import com.common.filedownloader.util.FileDownloadHelper;
import com.common.filedownloader.util.FileDownloadUtils;
import com.common.http.basecore.utils.LogInfo;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.activity.BaseActivity;
import com.v1.video.db.dao.DaoMaster;
import com.v1.video.db.dao.DaoMaster.DevOpenHelper;
import com.v1.video.db.dao.DaoSession;
import com.v1.video.db.service.CacheDB;
import com.v1.video.domain.GroupRedPointInfoConfig;
import com.v1.video.domain.GroupRedPointLastTimeConfig;
import com.v1.video.domain.MaiPaigeLiveInfo;
import com.v1.video.httpmanager.MemoryCache;
import com.v1.video.util.Logger;

import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;

public class AppContext extends CommonCoreApplication {

	private static AppContext mInstance = null;
	private static DaoMaster mDaoMaster;
	private static DaoSession mDaoSession;
	private MemoryCache mMemeryCache = new MemoryCache();
	/** 首页直播信息 */
	MaiPaigeLiveInfo liveInfo = null;
	/**
	 * 数据缓存集
	 * 
	 * @return
	 */
	public MemoryCache getMemeryCache() {
		return mMemeryCache;
	}

	// public static final String strKey = "7Ghd4hpzhQu142oOinKGSqfN"; //debug
	// ak
	// public static final String strKey = "okoifBdbI7v70fTBo855r3mY"; //my
	// debug ak
	public static final String strKey = "bguBNNGZS4xhkHlccmCg9iDf"; // vodone
																	// ak(现在使用的issmobile)

	public String urlH5Game = "";
	public String urlActivity1yuan = "";

	public static List<String> buddhism_titles;

	/**
	 * 存储所有Activity的当前生命周期状态
	 */
	private final Map<BaseActivity, Boolean> mActivityState = new ConcurrentHashMap<BaseActivity, Boolean>();
	private final HashMap<Object, Object> mAttribute = new HashMap<Object, Object>();
	public boolean isForeground = true;
	
	@Override
	public void onCreate() {
		super.onCreate();
		try {
			LogInfo.setIsDebug(BuildConfig.DEBUG);
			Constant.DEVICEID = AppUtils.generateDeviceId(this);
			Constant.PRODUCT_CODE = AppUtils.getChannelId(this);
			Constant.PRODUCT_VERSION = AppUtils.getVersion(this);
			initCoreParams();
			MobclickAgent.openActivityDurationTrack(false);// 禁止默认的页面统计方式，这样将不会再自动统计Activity。
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getApplicationContext())
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.memoryCache(new WeakMemoryCache())
					.discCacheSize(50 * 1024 * 1024)
					.memoryCacheSize(2 * 1024 * 1024).discCacheFileCount(100) // 缓存的文件数量
					.threadPoolSize(3).writeDebugLogs() // Remove for release
					.build();
			ImageLoader.getInstance().init(config);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mInstance = this;

		this.mMemeryCache = CacheDB.getInstance().getLoadCache();

		JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志
		JPushInterface.init(this); // 初始化 JPush
	}

	private void initCoreParams () {
		mHeadParamsInfo.setDevid(Constant.DEVICEID);
		mHeadParamsInfo.setPcode(Constant.PRODUCT_CODE);
		mHeadParamsInfo.setVersion(Constant.PRODUCT_VERSION);
		CoreConfiguration.setServerIp4Static(Constant.SERVER_IP_4_STATIC);
		CoreConfiguration.setServerIpPhp(Constant.SERVER_IP_PHP);
		CoreConfiguration.setServerIpUpload(Constant.SERVER_IP_UPLOAD);
		CoreConfiguration.setServerIpUser(Constant.SERVER_IP_USER);
		CoreConfiguration.initConfig(BuildConfig.DEBUG, mHeadParamsInfo);
		LogInfo.log("haitian", "mHeadParamsInfo = "+mHeadParamsInfo.toString());
	}
	private void initDownLoader(){
		/**
		 * just for cache Application's Context, and ':filedownloader' progress will NOT be launched
		 * by below code, so please do not worry about performance.
		 * @see FileDownloader#init(Context)
		 */
		FileDownloader.init(getApplicationContext(),
				new FileDownloadHelper.OkHttpClientCustomMaker() { // is not has to provide.
					@Override
					public OkHttpClient customMake() {
						// just for OkHttpClient customize.
						final OkHttpClient.Builder builder = new OkHttpClient.Builder();
						// you can set the connection timeout.
						builder.connectTimeout(15_000, TimeUnit.MILLISECONDS);
						// you can set the HTTP proxy.
						builder.proxy(Proxy.NO_PROXY);
						// etc.
						return builder.build();
					}
				});
		FileDownloadUtils.markConverted(getApplicationContext());
	}
	public static AppContext getInstance() {
		return mInstance;
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	// public static class MyGeneralListener implements MKGeneralListener {
	//
	// @Override
	// public void onGetNetworkState(int iError) {
	// if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
	// //Toast.makeText(AppContext.getInstance().getApplicationContext(),
	// "您的网络出错啦！",Toast.LENGTH_LONG).show();
	// }
	// else if (iError == MKEvent.ERROR_NETWORK_DATA) {
	// //Toast.makeText(AppContext.getInstance().getApplicationContext(),
	// "输入正确的检索条件！",Toast.LENGTH_LONG).show();
	// }
	// // ...
	// }
	//
	// @Override
	// public void onGetPermissionState(int iError) {
	// //非零值表示key验证未通过
	// if (iError != 0) {
	// //授权Key错误：
	// /* Toast.makeText(AppContext.getInstance().getApplicationContext(),
	// "请在 输入正确的授权Key,并检查您的网络连接是否正常！error: "+iError,
	// Toast.LENGTH_LONG).show();*/
	// AppContext.getInstance().m_bKeyRight = false;
	// }
	// else{
	// AppContext.getInstance().m_bKeyRight = true;
	// //Toast.makeText(AppContext.getInstance().getApplicationContext(),
	// "key认证成功", Toast.LENGTH_LONG).show();
	// }
	// }
	// }

	public static Bitmap bitmapHead = null;

	public static Bitmap getHeadBitmap() {
		if (bitmapHead != null) {
			return bitmapHead;
		} else {
			return null;
		}
	}

	public static void setHeadBitmap(Bitmap bm) {
		if (bitmapHead != null) {
			bitmapHead.recycle();
			bitmapHead = null;
		}
		bitmapHead = bm;
		// if(bm == null){
		// Logger.i("AppContext", "bm==null");
		// }else{
		// Logger.i("AppContext", "bm!!!!=null");
		// }
	}

	/**
	 * 保存圈子红点显示状态
	 * 
	 * @param userID
	 * @param info
	 */
	public static void saveGroupRedPoint(String userID,
			GroupRedPointInfoConfig info) {
		if (TextUtils.isEmpty(userID))
			return;
		SharedPreferences sf = PreferenceManager
				.getDefaultSharedPreferences(AppContext.getInstance());
		sf.edit()
				.putBoolean(userID + ".showOwnerGroupRedPoint",
						info.isShowOwnerGroupRedPoint())
				.putBoolean(userID + ".showTotalRedPoint",
						info.isShowTotalRedPoint())
				.putBoolean(userID + ".showFriendRedPoint",
						info.isShowFriendRedPoint())
				.putBoolean(userID + ".showFocusGroupRedPoint",
						info.isShowFocusGroupRedPoint()).commit();
	}

	/**
	 * 获取圈子红点状态
	 * 
	 * @param userID
	 * @return
	 */
	public static GroupRedPointInfoConfig getGroupRedPointInfo(String userID) {
		if (TextUtils.isEmpty(userID))
			return null;
		GroupRedPointInfoConfig gpc = new GroupRedPointInfoConfig();
		SharedPreferences sf = PreferenceManager
				.getDefaultSharedPreferences(AppContext.getInstance());
		gpc.setShowFocusGroupRedPoint(sf.getBoolean(userID
				+ ".showFocusGroupRedPoint", false));
		gpc.setShowFriendRedPoint(sf.getBoolean(userID + ".showFriendRedPoint",
				false));
		gpc.setShowOwnerGroupRedPoint(sf.getBoolean(userID
				+ ".showOwnerGroupRedPoint", false));
		gpc.setShowTotalRedPoint(sf.getBoolean(userID + ".showTotalRedPoint",
				false));
		return gpc;
	}

	/**
	 * 保存圈子红点最后访问时间
	 * 
	 * @param userID
	 * @param info
	 */
	public static void saveGroupRedPointLastTime(String userID,
			GroupRedPointLastTimeConfig info) {
		if (TextUtils.isEmpty(userID))
			return;
		SharedPreferences sf = PreferenceManager
				.getDefaultSharedPreferences(AppContext.getInstance());
		sf.edit()
				.putString(userID + ".friendGroupTime",
						info.getFriendGroupTime())
				.putString(userID + ".ownerGroupTime", info.getOwnerGroupTime())
				.putString(userID + ".focusGroupTime", info.getFocusGroupTime())
				.commit();
		Logger.i("PreferenceManager", "saveGroupRedPointLastTime");
	}

	/**
	 * 获取圈子红点最后访问时间
	 * 
	 * @param userID
	 * @return
	 */
	public static GroupRedPointLastTimeConfig getGroupRedPointLastTime(
			String userID) {
		if (TextUtils.isEmpty(userID))
			return null;
		GroupRedPointLastTimeConfig gplt = new GroupRedPointLastTimeConfig();
		SharedPreferences sf = PreferenceManager
				.getDefaultSharedPreferences(AppContext.getInstance());
		gplt.setFocusGroupTime(sf.getString(userID + ".focusGroupTime", ""));
		gplt.setOwnerGroupTime(sf.getString(userID + ".ownerGroupTime", ""));
		gplt.setFriendGroupTime(sf.getString(userID + ".friendGroupTime", ""));
		return gplt;
	}

	/**
	 * 
	 * @return
	 */
	public static DaoMaster getDaoMaster() {
		if (mDaoMaster == null) {
			DevOpenHelper helper = new DaoMaster.DevOpenHelper(
					AppContext.getInstance(), Constant.DB_NAME, null);
			mDaoMaster = new DaoMaster(helper.getWritableDatabase());
		}
		return mDaoMaster;
	}

	/**
	 * 
	 * @return
	 */
	public static DaoSession getDaoSession() {
		if (mDaoSession == null) {
			mDaoSession = AppContext.getDaoMaster().newSession();
		}
		return mDaoSession;
	}

	public MaiPaigeLiveInfo getLiveInfo() {
		return liveInfo;
	}

	public void setLiveInfo(MaiPaigeLiveInfo liveInfo) {
		this.liveInfo = liveInfo;
	}

	public void setUrlH5Game(String url) {
		if (url != null) {
			this.urlH5Game = url;
		}
	}

	public String getUrlH5Game() {
		return urlH5Game;
	}

	/** 设置一元夺宝的url */
	public void setActivityInfo(String url) {
		if (url != null) {
			this.urlActivity1yuan = url;
		}
	}

	/** 获取1元夺宝的url */
	public String getActivity1Yuan() {
		if (urlActivity1yuan != null && urlActivity1yuan.length() >= 5) {
			return this.urlActivity1yuan;
		} else {
			SharedPreferences sp = getSharedPreferences(Constant.APP_INFO,
					MODE_PRIVATE);
			String urlActivity = sp.getString("activity1yuan", "");
			return urlActivity;
		}
	}

	/**
	 * 播放视频、音乐其实就是靠这个类。
	 */
	private MediaPlayer mMediaPlayer = null;

	public synchronized MediaPlayer getmMediaPlayer(Uri mUri,
			SurfaceHolder mSurfaceHolder) {
		if (mMediaPlayer == null) {
			mMediaPlayer = new MediaPlayer();
			try {
				mMediaPlayer.setDataSource(this, mUri);
				mMediaPlayer.setDisplay(mSurfaceHolder);
				mMediaPlayer.prepareAsync();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return mMediaPlayer;
	}

	public synchronized MediaPlayer getmMediaPlayer() {

		return mMediaPlayer;
	}

	public void setmMediaPlayer(MediaPlayer mMediaPlayer) {
		this.mMediaPlayer = mMediaPlayer;
	}

	public void clearMediaPlayer() {
		if (mMediaPlayer != null) {
			// if(mMediaPlayer.isPlaying()){
			// mMediaPlayer.stop();
			// }
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}

	public Object getAttribute(Object key) {
		return mAttribute.get(key);
	}

	public void setAttribute(Object key, Object value) {
		mAttribute.put(key, value);
	}

	public boolean isTopApplication() {
		for (Map.Entry<BaseActivity, Boolean> entry : mActivityState.entrySet()) {
			if (entry.getValue()) {
				return true;
			}
		}
		return false;
	}
	
	public void setActivityState(BaseActivity activity, Boolean isVisible) {
        mActivityState.put(activity, isVisible);
    }
	
	public void removeActivityState(BaseActivity activity) {
        mActivityState.remove(activity);
    }
	
	/**
	 * 保存perference
	 * @param key
	 * @param value
	 */
    public static void savePreference(String key,String value){
    	if(TextUtils.isEmpty(key) || TextUtils.isEmpty(value))
    		return;
    	SharedPreferences sf=PreferenceManager.getDefaultSharedPreferences(AppContext.getInstance());
    	sf.edit()
    	.putString(key, value)
    	.commit();
    }
    
    /**
     * 获取perference
     * @param key
     * @return
     */
    public static String getPreference(String key){
    	if(TextUtils.isEmpty(key))
    		return "";
    	SharedPreferences sf=PreferenceManager.getDefaultSharedPreferences(AppContext.getInstance());
    	if(!sf.contains(key))
    		return "";
    	return sf.getString(key, "");
    } 
}
